package com.exp3;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.BlockingDeque;

import javax.swing.JOptionPane;

public class ReadFromSocket extends Thread {
	private BlockingDeque<String> list;

	public ReadFromSocket(BlockingDeque<String> list) {
		this.list = list;
	}

	@Override
	public void run() {
		try {
			InetAddress group = InetAddress.getByName("228.0.0.1");
			int port = 4000;
			JOptionPane.showMessageDialog(null, "连接服务器成功");
			try(MulticastSocket ms = new MulticastSocket(port)){
				ms.joinGroup(group);
				byte[] buffer = new byte[1024];
				while(true) {
					DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
					ms.receive(dp);
					list.add(new String(dp.getData(), 0, dp.getLength()));
					Thread.sleep(100);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}